#!/bin/bash
#$Id$
#
# ore-value.sh - show ore and ice values:
#     ore value by volume before refining or mfg.
#     ore value by volume after refining
# 
# (c) 2010 bitmech.com. See LICENSE file for details.
#
# accept command line arguments 
#   for price comparison type:
#   -pZ                 where Z is either b for buy or s for sell;
#   for output type:
#   -oY                 where Y is either b for before refining or a for after;
#   for system type:
#   -S[system]          for orders in system
#   for refinery skills:
#     -rX		where X is refinery efficiency;
#     -sABCDEFG...      where [A-S] are level 0-5 of skills:
#         A->refining
#         B->veldspar processing
#         C->scordite processing
#         D->pyroxeres processing
#         E->plagioclase processing
#         F->omber processing
#         G->kernite processing
#         H->jaspet processing
#         I->hemorphite processing
#         J->hedbergite processing
#         K->gneiss processing
#         L->dark ochre processing
#         M->spodumain processing
#         N->crokite processing
#         O->bistot processing
#         P->arkonor processing
#         Q->mercoxit processing
#         R->refinery processing
#         S->ice processing
#
#     ...the rest are reserved for future use. If not specified, defaults are
#     set below.
#
# DEFAULTS
o=b 
p=b
r=35
s=0000000000000000000

#
# staticdb csv exports root
DBROOT=../staticdb

#
# CSV hash of items by type and volume
VOLCSV=${DBROOT}/items-by-vol.csv

#
# CSV hash of items by mat (no key)
MATCSV=${DBROOT}/items-by-mat.csv

#
# CSV hash of items by batch size 
BATCSV=${DBROOT}/items-by-bat.csv

#
# market API wrapper root
MARKETAPIROOT=../evecentral

#
# market API wrapper script
MARKETAPI=${MARKETAPIROOT}/market-download.sh

#
# market API output dir
MARKETDATA=./marketdata

function getmedian {
    itemid="$1"
    pricetype="$2"
    case $pricetype in
        b) p=buy;;
        s) p=sell;;
        m) p=median;;
    esac
    if [ "$p" = "median" ]; then
        sellprice=$(getmedian "$itemid" "s")
        p="buy"
    fi
    #
    # update the price data
    ${MARKETAPI} -i${itemid} -o${MARKETDATA} -s${S} >/dev/null 2>&1
    pricedata=${MARKETDATA}/orders-${itemid}.xml
    #
    # get rough median buy price per unit of item
    buytagline=$(grep -n "<${p}_orders>" ${pricedata} | awk -F: '{print $1}')
    if [ "$buytagline" = "" ]; then
        echo "0"
        return
    fi
    bids=$(sed "1,${buytagline}d" ${pricedata}                          \
        | grep "<price>"                                                \
        | awk -F\> '{print $2}'                                         \
        | awk -F\< '{print $1}' | sort -n)
    numbids=$(echo ${bids} | wc -w)
    numbids=$(expr $numbids / 2)
    median=$(echo ${bids} | awk -v n="${numbids}" '{print $n}')

    if [ "$p" = "median" ];
    then
        median=$(($median + $sellprice))
        median=$(($median / 2))
    fi
    echo "${median}"
}

#
# parse arguments
args="$@"
OPTIND=1
while getopts ":o:r:s:p:S:" opt $args
do
    case $opt in
      o) o="${OPTARG}";;
      r) r="${OPTARG}";;
      s) s="${OPTARG}";;
      p) p="${OPTARG}";;
      S) S="${OPTARG}";;
      *) echo "invalid arguments. Exiting."; exit 1;;
    esac
done
#
# verify args
if [ \( "$o" != "a" \) -a \( "$o" != "b" \) ]; then
    echo "-oY, Y must be either b (before refining) or a (after). Exiting."
    exit 1
fi
if [ \( "$p" != "b" \) -a \( "$p" != "s" \) -a \( "$p" != "m" \) ]; then
    echo "-pZ, Z must be either b (buy),s (sell),m (median). Exiting."
    exit 1
fi
if [ \( "$r" != "35" \) -a \( "$o" != "50" \) ]; then
    echo "-rX, X must be either 35 or 50. Exiting."
    exit 1
fi
echo "$s" | egrep -e '[0-5]{19}' >/dev/null 2>&1
if [ "$?" != "0" ]; then
    echo "-s[A-S], exactly 19 skill levels of [0-5] must be specified. Exiting."
    exit 1
fi

#
# ice and ore types we care about
ORES="Arkonor Bistot Blue+Ice Clear+Icicle Crokite Dark+Ochre Glacial+Mass Gneiss Hedbergite Hemorphite Jaspet Kernite Mercoxit Omber Plagioclase Pyroxeres Scordite Spodumain Veldspar White+Glaze"

for ore in $ORES
do
    thisore="'${ore}'"; thisore=$(echo ${thisore} | sed 's/+/ /')
    itemid=$(grep "${thisore}" ${VOLCSV} | awk -F, '{print $1}')
    itemvol=$(grep "${thisore}" ${VOLCSV} | awk -F, '{print $3}')
    if [ "$o" = "b" ]; then
        median=$(getmedian "$itemid" "${p}")
        iskdensity=$(echo "scale=2; ${median}/${itemvol}" | bc)
        echo "${itemid},'${ore}',${iskdensity}" | sed 's/+/ /'
    fi 
    if [ "$o" = "a" ]; then
        materials=$(egrep "^${itemid}," ${MATCSV}                       \
            | awk -F, '{print $2","$3}'                                 \
            | xargs)
        total=0; for pair in ${materials}
        do
            mineralid=$(echo "${pair}" | awk -F, '{print $1'})
            quantity=$(echo "${pair}" | awk -F, '{print $2'})
            median=$(getmedian "$mineralid" "${p}")
            subtotal=$(echo "scale=2; ${quantity}*${median}" | bc)
            total=$(echo "scale=2; ${total}+${subtotal}" | bc)
        done 
        batchsize=$(egrep "^${itemid}," ${BATCSV}                       \
            | awk -F, '{print $2}') 
        batchvol=$(echo "scale=2; ${batchsize}*${itemvol}" | bc)
        iskdensity=$(echo "scale=2; ${total}/${batchvol}" | bc)
        echo "${itemid},'${ore}',${iskdensity}" | sed 's/+/ /'
    fi 
done | sort -rn -t, -k3
